package com.caigou.modules.data.ui.all

import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.adapter.CommentItemAdapter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.screenCapture
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.data.R
import com.caigou.modules.data.bean.ALlYearDetailBean
import com.caigou.modules.data.databinding.ActivityAllYearDetailBinding
import com.caigou.modules.data.viewmodel.AllYearViewModel
import com.caigou.modules.data.viewmodel.LikeViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/29
 */
@Route(path = RouterPath.Data.PAGE_ALL_YEAR_DETAIL)
@AndroidEntryPoint
class AllYearDetailActivity : BaseActivity() {

    private lateinit var binding: ActivityAllYearDetailBinding
    private val allYearViewModel: AllYearViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.DATA_ID)
    var dataId = -1

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 0

    private val commentItemAdapter: CommentItemAdapter by lazy {
        CommentItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAllYearDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.allYearDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.allYearDetailSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchAllYearDetail()
            }
        }

        commentItemAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                commentItemAdapter.loadMoreModule.isEnableLoadMore = true
                fetchCommentList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.allYearDetailRecyclerViewComment.run {
            layoutManager = LinearLayoutManager(this@AllYearDetailActivity)
            adapter = commentItemAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@AllYearDetailActivity))
        }

        commentItemAdapter.setOnItemChildClickListener { _, view, position ->
            val item = commentItemAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_content -> {
                    ARouter.getInstance().build(RouterPath.Data.PAGE_COMMENT_DETAIL)
                        .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                        .withInt(AppConstants.DATA_TYPE, 2)
                        .navigation()
                }
                R.id.item_comment_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            return@setOnItemChildClickListener
                        }
                        likeViewModel.setCommentLike(item.replyId, 2, AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId)
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Data.PAGE_COMMENT_REPLY)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, item)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.allYearDetailRgSelector.setOnCheckedChangeListener { group, _ ->
            sort = when (group.checkedRadioButtonId) {
                binding.allYearDetailBtnSequential.id -> 1
                binding.allYearDetailBtnReverse.id -> 0
                else -> 0
            }
            page = 1
            fetchCommentList()
        }

        binding.allYearTvBack.setOnClickListener {
            finish()
        }

        binding.allYearDetailLlShare.setOnClickListener {
            val bitmap = binding.allYearDetailLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            fetchCommentList()
        }

        fetchAllYearDetail()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(allYearViewModel.allYearDetailLiveData, ::handleGetAllYearDetail)
        observe(allYearViewModel.commentListLiveData, ::handleGetCommentList)
        observe(likeViewModel.dataLikeLiveData, ::handleSetDataLike)
        observe(likeViewModel.commentLikeLiveData, ::handleSetCommentLike)
    }

    private fun handleGetAllYearDetail(result: Resource<ALlYearDetailBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    handleDetailUI(this)
                    fetchCommentList()
                }
            }
        }
    }

    private fun handleGetCommentList(result: Resource<CommentBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论列表异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.allYearDetailLlEmptyComment.visibility = View.VISIBLE
                    binding.allYearDetailRecyclerViewComment.visibility = View.GONE
                    return
                }
                if (result.data!!.list.isNullOrEmpty()) {
                    binding.allYearDetailLlEmptyComment.visibility = View.VISIBLE
                    binding.allYearDetailRecyclerViewComment.visibility = View.GONE
                } else {
                    binding.allYearDetailLlEmptyComment.visibility = View.GONE
                    binding.allYearDetailRecyclerViewComment.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    commentItemAdapter.setList(result.data!!.list)
                } else {
                    commentItemAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    commentItemAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    commentItemAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleSetDataLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchAllYearDetail()
                }
            }
        }
    }

    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.allYearDetailSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    fetchCommentList()
                }
            }
        }
    }

    private fun handleDetailUI(bean: ALlYearDetailBean) {
        binding.allYearDetailTvTitle.text = bean.title
        bean.content = bean.content.replace("\\r", "\r")
        bean.content = bean.content.replace("\\n", "\n")
        bean.content = bean.content.replace("\\t", "\t")

        binding.allYearDetailTvContent.text = Html.fromHtml(bean.content)

        if (AppBackgroundInfo.instance.hasLogin) {
            if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
                binding.allYearDetailIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this, AppBackgroundInfo.instance.userBean!!.headImg, binding.allYearDetailIvMyAvatar)
            }
        } else {
            binding.allYearDetailIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
        }

        binding.allYearDetailTvLikeNum.text = bean.likeCount.toString()
        if (bean.like) {
            binding.allYearDetailIvLike.setImageResource(R.drawable.img_data_like)
            binding.allYearDetailTvLikeNum.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.allYearDetailIvLike.setImageResource(R.drawable.img_data_unlike)
            binding.allYearDetailTvLikeNum.setTextColor(Color.parseColor("#505050"))
        }
        binding.allYearDetailLlLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (bean.like) {
                    showToast("您已经点过赞了")
                } else {
                    likeViewModel.setDataLike(bean.dataId, 2, AppBackgroundInfo.instance.userBean!!.userId)
                }
            } else {
                showToast("请您先登录")
            }
        }

        binding.allYearDetailTvCommentNum.text = bean.replyCount.toString()

        binding.allYearDetailBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Data.PAGE_DATA_REPLY)
                    .withInt(AppConstants.DATA_ID, bean.dataId)
                    .withInt(AppConstants.DATA_TYPE, 2)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.allYearDetailLlComment.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Data.PAGE_DATA_REPLY)
                    .withInt(AppConstants.DATA_ID, bean.dataId)
                    .withInt(AppConstants.DATA_TYPE, 2)
                    .withString(AppConstants.RECEIVER_ID, "")
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }
    }

    private fun fetchAllYearDetail() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        allYearViewModel.getAllYearDetail(dataId, userId)
    }

    private fun fetchCommentList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        allYearViewModel.getCommentList(page, limit, dataId, sort, userId)
    }

}